package com.vone.vmq;

import android.Manifest;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.media.RingtoneManager;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.NotificationManagerCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.vone.qrcode.R;
import com.vone.vmq.util.Constant;
import com.google.zxing.activity.CaptureActivity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.lang.ref.WeakReference;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.Set;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity{


    private EditText et_account;
    private EditText et_account_pwd;
    private EditText et_pay_pwd;
    private Button btn_save;

    private boolean isOk = false;
    private static String TAG = "MainActivity";

    private static String host;
    private static String key;

    int id = 0;

    public static final int MSG_TOKEN_MISS = 0;
    public static final int MSG_RERUSET_ERROR = 1;

    CountDownTimer timer;

    MyHandler myHandler;
    //创建静态内部类
    private static class MyHandler extends Handler{
        //持有弱引用MainActivity,GC回收时会被回收掉.
        private final WeakReference<MainActivity> mAct;
        public MyHandler(MainActivity mainActivity){
            mAct =new WeakReference<MainActivity>(mainActivity);
        }
        @Override
        public void handleMessage(Message msg) {
            MainActivity mainAct=mAct.get();
            super.handleMessage(msg);
            if(mainAct!=null){
                //执行业务逻辑
                if(msg.what==MSG_TOKEN_MISS){
                    String str1 = msg.getData().getString("msg");
                    Toast.makeText(mainAct, "登录已失效，请重新登录", Toast.LENGTH_SHORT).show();
                }else if(msg.what==MSG_RERUSET_ERROR){
                    Toast.makeText(mainAct, "请求失败", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        myHandler = new MyHandler(this);

        et_account = (EditText) findViewById(R.id.et_account);
        et_account_pwd = (EditText) findViewById(R.id.et_account_pwd);
        et_pay_pwd = (EditText) findViewById(R.id.et_pay_pwd);
        btn_save = (Button) findViewById(R.id.btn_save);



        //检测通知使用权是否启用
        if (!isNotificationListenersEnabled()) {
            //跳转到通知使用权页面
            gotoNotificationAccessSetting();
        }
        //重启监听服务
        toggleNotificationListenerService(this);



        //读入保存的配置数据并显示
        SharedPreferences read = getSharedPreferences("vone", MODE_PRIVATE);
        host = read.getString("host", "");
        key = read.getString("key", "");

//        if (host!=null && key!=null && host!="" && key!=""){
//            txthost.setText(" 通知地址："+host);
//            txtkey.setText(" 通讯密钥："+key);
//            isOk = true;
//        }
        btn_save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String account = et_account.getText().toString();
                String loginPwd = et_account_pwd.getText().toString();
                String payPwd = et_pay_pwd.getText().toString();
                doLogin(account,loginPwd,payPwd);
            }
        });

    }


    //各种权限的判断
    private void toggleNotificationListenerService(Context context) {
        PackageManager pm = context.getPackageManager();
        pm.setComponentEnabledSetting(new ComponentName(context, NeNotificationService2.class),
                PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);

        pm.setComponentEnabledSetting(new ComponentName(context, NeNotificationService2.class),
                PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);

        Toast.makeText(MainActivity.this, "监听服务启动中...", Toast.LENGTH_SHORT).show();
    }
    public boolean isNotificationListenersEnabled() {
        String pkgName = getPackageName();
        final String flat = Settings.Secure.getString(getContentResolver(), "enabled_notification_listeners");
        if (!TextUtils.isEmpty(flat)) {
            final String[] names = flat.split(":");
            for (int i = 0; i < names.length; i++) {
                final ComponentName cn = ComponentName.unflattenFromString(names[i]);
                if (cn != null) {
                    if (TextUtils.equals(pkgName, cn.getPackageName())) {
                        return true;
                    }
                }
            }
        }
        return false;
    }
    protected boolean gotoNotificationAccessSetting() {
        try {
            Intent intent = new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS");
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
            return true;

        } catch (ActivityNotFoundException e) {//普通情况下找不到的时候需要再特殊处理找一次
            try {
                Intent intent = new Intent();
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                ComponentName cn = new ComponentName("com.android.settings", "com.android.settings.Settings$NotificationAccessSettingsActivity");
                intent.setComponent(cn);
                intent.putExtra(":settings:show_fragment", "NotificationAccessSettings");
                startActivity(intent);
                return true;
            } catch (Exception e1) {
                e1.printStackTrace();
            }
            Toast.makeText(this, "对不起，您的手机暂不支持", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
            return false;
        }
    }



    public static String md5(String string) {
        if (TextUtils.isEmpty(string)) {
            return "";
        }
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
            byte[] bytes = md5.digest(string.getBytes());
            String result = "";
            for (byte b : bytes) {
                String temp = Integer.toHexString(b & 0xff);
                if (temp.length() == 1) {
                    temp = "0" + temp;
                }
                result += temp;
            }
            return result;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }



    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case Constant.REQ_PERM_CAMERA:
                // 摄像头权限申请
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 获得授权
                   // startQrCode(null);
                } else {
                    // 被禁止授权
                    Toast.makeText(MainActivity.this, "请至权限中心打开本应用的相机访问权限", Toast.LENGTH_LONG).show();
                }
                break;
            case Constant.REQ_PERM_EXTERNAL_STORAGE:
                // 文件读写权限申请
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 获得授权
                    //startQrCode(null);
                } else {
                    // 被禁止授权
                    Toast.makeText(MainActivity.this, "请至权限中心打开本应用的文件读写权限", Toast.LENGTH_LONG).show();
                }
                break;
        }
    }


    private void doLogin(final String account,final String loginPwd,final String payPwd){

        OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody requestBody = new FormBody.Builder()
                .add("username",account)
                .add("password",loginPwd)
                .build();

//        Headers header = new Headers.Builder()
//                .add("","")
//                .build();

        Request request = new Request.Builder()
                .url("http://www.otc888.cc/uc/login")
                .method("POST",requestBody)
//                .headers(header)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d(TAG, "onResponse  doLogin: 请求失败");
                myHandler.sendEmptyMessage(MSG_RERUSET_ERROR);

            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if(!response.isSuccessful()){
                    myHandler.sendEmptyMessage(MSG_RERUSET_ERROR);
                    return;
                }

                String jsonStr = response.body().string();
                Log.d(TAG, "onResponse  doLogin: "+jsonStr);
                try {
                    JSONObject jsonObject = new JSONObject(jsonStr);
                    int code = jsonObject.getInt("code");
                    if(code==0){
                        JSONObject dataJson = jsonObject.getJSONObject("data");
                        String token = dataJson.getString("token");
                        Log.d(TAG, "onResponse  token: " + token);
                        savaToken(token);
                        saveConfig(account,loginPwd,payPwd);
                    }else{
                        String msg = jsonObject.getString("message");
                        toast(msg);
                    }


                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
    }

    private void savaToken(String token){
        SharedPreferences write = getSharedPreferences("vone", Context.MODE_PRIVATE);
        write.edit().putString("token",token).commit();
    }

    private void saveConfig(String account,String loginPwd,String payPwd){
        unableViews();
        SharedPreferences write = getSharedPreferences("vone", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = write.edit();
        editor.putString("account",account);
        editor.putString("loginPwd",loginPwd);
        editor.putString("payPwd",payPwd);
        editor.commit();
    }

    void unableViews(){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                et_account.setEnabled(false);
                et_account_pwd.setEnabled(false);
                et_pay_pwd.setEnabled(false);
                btn_save.setEnabled(false);
                Toast.makeText(MainActivity.this,"配置成功",Toast.LENGTH_SHORT).show();
            }
        });

    }

    void toast(final String msg){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(MainActivity.this,msg,Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(timer!=null){
            timer.cancel();
            timer=null;
        }

    }

    private void startTimeCount(int hour){
        Toast.makeText(MainActivity.this,"程序将在"+hour+"小时后退出",Toast.LENGTH_SHORT).show();
        timer = new CountDownTimer(hour*60*60*1000+2*1000,1*60*1000) {
            @Override
            public void onTick(long l) {
            }
            @Override
            public void onFinish() {
                finishAffinity();
                System.exit(0);
            }
        };
        timer.start();
    }
}
